<!--
 * Copyright © 2023
 * @Author: zhangxiang
 * @Date: 2023-07-24 17:26:06
 * @LastEditors: zhangxiang
 * @LastEditTime: 2023-07-24 18:02:40
 * @Description:
 *
-->

<template>
  <el-form
    ref="form"
    class="vm-form-openstack"
    :rules="rules"
    :model="form"
    label-width="80px"
    size="medium"
  >
    <el-form-item
      v-if="scene != 'orchestrate'"
      class="item"
      label="云服务商"
      prop="cloudProvider"
    >
      <el-select
        v-model="form.cloudProvider"
        placeholder="请选择云服务商"
        style="width: 100%"
        :disabled="true"
      >
        <el-option
          v-for="item in cloudProviderOptions"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
    </el-form-item>
    <el-form-item
      v-if="scene != 'orchestrate'"
      class="item right"
      label="云账户"
      prop="cloudAccountName"
    >
      <el-select
        v-model="form.cloudAccountName"
        placeholder="请选择云账户"
        style="width: 100%"
        no-data-text="请选择云服务商"
      >
        <el-option
          v-for="item in cloudAccountNameOptions"
          :key="item.cloudAccountName"
          :label="item.cloudAccountName"
          :value="item.cloudAccountName"
        />
      </el-select>
    </el-form-item>
    <el-form-item label="主机名称" prop="vmName">
      <el-input v-model="form.vmName" placeholder="请输入主机名称" />
    </el-form-item>
    <el-form-item label="可用域" prop="zone">
      <el-select
        v-model="form.zone"
        placeholder="请选择可用域"
        style="width: 100%"
      >
        <el-option
          v-for="item in zoneOptions"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
    </el-form-item>
    <el-form-item label="镜像" prop="imageId">
      <el-row type="flex" justify="center">
        <el-select
          v-model="form.imageOs"
          placeholder="请选择操作系统"
          style="width: 35%; margin-right: 10px"
          @change="imageOsChange"
        >
          <el-option
            v-for="item in imageOsOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <el-select
          v-model="form.imageId"
          placeholder="请选择相应镜像"
          no-data-text="请选择合适的账户"
          style="width: 65%"
          filterable
        >
          <el-option
            v-for="item in imageIdOptions"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-row>
    </el-form-item>
    <el-form-item label="规格" prop="flavorId">
      <el-row type="flex" justify="center">
        <el-select
          v-model="form.cpuCount"
          placeholder="请选择vCPUs"
          style="flex: 1; margin-right: 5px"
          @change="flavorSelectorChange($event, 'cpuCount')"
        >
          <el-option
            v-for="item in cpuCountOptions"
            :key="item.value"
            :label="item.label + 'vCPUs'"
            :value="item.value"
          />
        </el-select>
        <el-select
          v-model="form.memSize"
          placeholder="请选择内存"
          style="flex: 1; margin-right: 5px"
          @change="flavorSelectorChange($event, 'memSize')"
        >
          <el-option
            v-for="item in memSizeOptions"
            :key="item.value"
            :label="item.label + 'GiB'"
            :value="item.value"
          />
        </el-select>
        <el-select
          v-model="form.flavorId"
          placeholder="请选择规格"
          no-data-text="请选择合适的过滤条件"
          style="flex: 2"
          :loading="loadingFlavorIdOptions"
        >
          <el-option
            v-for="item in flavorIdOptions"
            :key="item.id"
            :label="
              item.name + ' (' + item.cpuCount + 'C | ' + item.memSize + 'G)'
            "
            :value="item.id"
          />
        </el-select>
      </el-row>
    </el-form-item>
    <el-form-item label="登录密码" prop="loginPwd">
      <el-row type="flex" align="middle">
        <el-input
          v-model="form.loginPwd"
          placeholder="请输入登录密码"
          :disabled="true"
        />
        <el-tooltip
          effect="dark"
          content="用于设置登录虚机的root密码"
          placement="top"
        >
          <i
            class="el-icon-info icon"
            style="font-size: 18px; margin-left: 10px"
          ></i>
        </el-tooltip>
      </el-row>
    </el-form-item>
    <el-form-item label="标签" prop="vmTags">
      <VmTags :vm-tags.sync="form.vmTags" />
    </el-form-item>
  </el-form>
</template>

<script>
import resSelectorMixin from '@/views/mixin/resSelector.js'
import {
  queryImage,
  queryInstanceType,
  getPrivateZones
} from '@/api/cn-resource'
import { CLOUD_OPENSTACK_IMAGE_OS, VCPUS, MEM_SIZE } from '@/utils/constant'
import debounce from 'lodash/debounce'
import VmTags from '@/views/cn-resource/vm/components/VmTags.vue'

export default {
  name: 'VMFormOpenstack',
  components: {
    VmTags
  },
  mixins: [resSelectorMixin],
  props: {
    scene: {
      type: String,
      default: 'create'
    },
    info: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    /**
     * @description: 校验 登录密码
     * @param {*} rule
     * @param {*} value
     * @param {*} callback
     * @return {*}
     */
    var validateLoginPwd = (rule, value, callback) => {
      if (this.form.cloudProvider === '阿里云') {
        const reg =
          /^(?![a-zA-Z]+$)(?![A-Z0-9]+$)(?![A-Z\W_]+$)(?![a-z0-9]+$)(?![a-z\W_]+$)(?![0-9\W_]+$)[a-zA-Z0-9\W_]{8,30}$/
        if (reg.test(value)) {
          callback()
        } else {
          callback(
            new Error(
              '密码长度8~30字符，须同时包含大写字母、小写字母、数字、特殊字符中的任意三种'
            )
          ) // 抛出异常
        }
      } else if (this.form.cloudProvider === '华为云') {
        const reg =
          /^(?![a-zA-Z]+$)(?![A-Z0-9]+$)(?![A-Z\W_]+$)(?![a-z0-9]+$)(?![a-z\W_]+$)(?![0-9\W_]+$)[a-zA-Z0-9\W_]{8,26}$/
        if (reg.test(value)) {
          callback()
        } else {
          callback(
            new Error(
              '密码长度8~26字符，须同时包含大写字母、小写字母、数字、特殊字符中的任意三种'
            )
          ) // 抛出异常
        }
      } else {
        if (value === '') {
          callback(new Error('请输入密码')) // 抛出异常
        } else {
          callback()
        }
      }
    }
    /**
     * @description: 校验vmTags
     * @param {*} rule
     * @param {*} value
     * @param {*} callback
     * @return {*}
     */
    var validateVmTags = (rule, value, callback) => {
      if (Array.isArray(this.form.vmTags) && this.form.vmTags.length > 0) {
        // 不为空
        const reg = /^([a-zA-Z\d-_\\\/\:\.\s])*$/ // 校验的正则
        let hasIllegal = false // 是否存在不合法
        for (const item of this.form.vmTags) {
          if (
            item.key === '' ||
            !reg.test(item.key) ||
            item.value === '' ||
            !reg.test(item.value) // 数据为空或不符合规则
          ) {
            // 存在不合法
            hasIllegal = true
            break
          }
        }
        if (hasIllegal) {
          callback(new Error('存在不合法的标签键值')) // 抛出异常
        } else {
          callback()
        }
      } else {
        callback()
      }
    }
    return {
      skipGetCloudAccount: false,
      zoneOptions: [],
      imageOsOptions: CLOUD_OPENSTACK_IMAGE_OS,
      imageIdOptions: [],
      loadingFlavorIdOptions: false,
      flavorIdOptions: [],
      cpuCountOptions: VCPUS,
      memSizeOptions: MEM_SIZE,
      form: {
        cloudProvider: '', // 云服务商
        cloudAccountName: '', // 云账户
        vmName: '', // 主机名称
        zone: '', // 可用区
        imageOs: CLOUD_OPENSTACK_IMAGE_OS[0].value, // 镜像系统
        imageId: '', // 镜像
        cpuCount: '', // cpu
        memSize: '', // 内存
        flavorId: '', // 规格
        loginPwd: '123456', // 登录密码
        vmTags: [] // 标签
      },
      rules: {
        cloudProvider: [
          { required: true, message: '请选择云服务商', trigger: 'change' }
        ],
        cloudAccountName: [
          { required: true, message: '请选择云账户', trigger: 'change' }
        ],
        vmName: [
          { required: true, message: '请输入主机名称', trigger: 'blur' }
        ],
        zone: [{ required: true, message: '请选择可用区', trigger: 'change' }],
        imageOs: [
          { required: true, message: '请选择操作系统', trigger: 'change' }
        ],
        imageId: [
          { required: true, message: '请选择相应镜像', trigger: 'change' }
        ],
        flavorId: [
          { required: true, message: '请选择规格', trigger: 'change' }
        ],
        loginPwd: [{ required: true, validator: validateLoginPwd }],
        vmTags: [{ validator: validateVmTags }]
      },
      flavorQueryDebounce: null,
      imageIdQueryDebounce: null
    }
  },
  computed: {
    /**
     * @description: 规格相关参数
     * @return {*}
     */
    flavorParam() {
      return {
        cloudAccountName: this.form.cloudAccountName,
        cpuCount: this.form.cpuCount,
        memSize: this.form.memSize
      }
    },
    /**
     * @description: 镜像相关参数
     * @return {*}
     */
    imageIdParam() {
      return {
        cloudAccountName: this.form.cloudAccountName,
        imageOs: this.form.imageOs
      }
    }
  },
  watch: {
    /**
     * @description: 监听
     * @return {*}
     */
    info: {
      handler(newVal) {
        if (newVal) {
          this.form = Object.assign(this.form, this.info)
          this.form.loginPwd = this.form.loginPwd || '123456'
        }
      },
      immediate: true,
      deep: true
    },
    /**
     * @description: 监听镜像相关参数
     * @return {*}
     */
    imageIdParam: {
      handler(newVal) {
        if (this.form.cloudAccountName && this.form.imageOs) {
          if (!this.imageIdQueryDebounce) {
            // 创建防抖函数
            this.imageIdQueryDebounce = debounce(() => {
              this.getImageList()
            }, 300)
          }
          this.imageIdQueryDebounce()
        }
      },
      immediate: true,
      deep: true
    },
    /**
     * @description: 监听规格相关参数
     * @return {*}
     */
    flavorParam: {
      handler(newVal) {
        if (this.form.cloudAccountName) {
          if (!this.flavorQueryDebounce) {
            // 创建防抖函数
            this.flavorQueryDebounce = debounce(() => {
              this.getFlavorList()
            }, 300)
          }
          this.flavorQueryDebounce()
        }
      },
      immediate: true,
      deep: true
    },
    /**
     * @description: 云账户监听
     * @return {*}
     */
    'form.cloudAccountName': {
      handler(newVal) {
        if (newVal) {
          // 私有云
          // 请求可用域
          this.getPrivateZones()
        }
      },
      immediate: true
    }
  },
  created() {
    this.skipGetCloudAccount = this.scene === 'orchestrate'
  },
  methods: {
    /**
     * @description: 获取私有云可用域
     * @return {*}
     */
    getPrivateZones() {
      getPrivateZones({
        cloudAccountName: this.form.cloudAccountName
      }).then((res) => {
        const zones =
          res.data && Array.isArray(res.data.zones) ? res.data.zones : []
        this.zoneOptions = zones.map((item) => {
          return {
            value: item,
            label: item
          }
        })
      })
    },
    /**
     * @description: 获取规格
     * @return {*}
     */
    getFlavorList() {
      this.loadingFlavorIdOptions = true
      queryInstanceType({
        cloudProvider: this.form.cloudProvider,
        cloudAccountName: this.form.cloudAccountName,
        cpuCount: this.form.cpuCount,
        memSize: this.form.memSize
      })
        .then((res) => {
          this.flavorIdOptions = Array.isArray(res.data)
            ? res.data.slice(0, Math.min(res.data.length, 100))
            : []
        })
        .finally(() => {
          this.loadingFlavorIdOptions = false
        })
    },
    /**
     * @description: 获取镜像
     * @return {*}
     */
    getImageList() {
      queryImage({
        cloudProvider: this.form.cloudProvider,
        cloudAccountName: this.form.cloudAccountName,
        osPlatform: this.form.imageOs
      }).then((res) => {
        this.imageIdOptions = Array.isArray(res.data) ? res.data : []
      })
    },
    /**
     * @description: 镜像操作系统选择
     * @param {*} val
     * @return {*}
     */
    imageOsChange(val) {
      // 刷新镜像
      this.form.imageId = ''
      this.imageIdOptions = []
    },
    /**
     * @description: 规格过滤切换
     * @param {*} val
     * @param {*} type
     * @return {*}
     */
    flavorSelectorChange(val, type) {
      // 清空规格
      this.form.flavorId = ''
      this.flavorIdOptions = []
    },
    /**
     * @description: 校验
     * @return {*}
     */
    validateForm(callback) {
      this.$refs.form.validate((valid, obj) => {
        if (valid) {
          callback(this.form)
        }
      })
    }
  }
}
</script>

<style lang="less" scoped>
@import "@/assets/css/common.less";
.vm-form-openstack {
  .item {
    display: inline-block;
    width: calc(50% - 7.5px);
    &.right {
      margin-left: 15px;
    }
  }
}
</style>
